#include <rtdbg.h>
#include "rtthread.h"
#include "sys/socket.h"   /*使用BSD Socket，需要包含socket.h*/
#include "netdb.h"
#include "string.h"
#include "finsh.h"
#define PORT 5001
#define IP_ADDR "192.168.0.200"
#define TCPRV_BUFSZ 512 
extern void MX_LWIP_Init(void);
static const char send_data[]="This is TCP Client";
static rt_thread_t tcp_client_thread_ptr = RT_NULL;

void tcp_client_thread(void* parameter)
{
	int sock=-1;
	int bytes_received;
	char* recv_data;
	/* LWIP_IPV4 */
	struct sockaddr_in server_addr;
	//struct hostent *host;
	recv_data=rt_malloc(TCPRV_BUFSZ);
	while(1)
	{
		if(recv_data==RT_NULL)
		{
			LOG_E("No memory");
			return;
		}
		if((sock=socket(AF_INET,SOCK_STREAM,0))==-1)   /*创建socket*/
		{  
			LOG_E("socket error");
			rt_free(recv_data);
			return;
		}
		/*初始化预连接的服务器地址*/
		server_addr.sin_family=AF_INET;
		server_addr.sin_port=htons(PORT);
		server_addr.sin_addr.s_addr = inet_addr(IP_ADDR);
		//host = gethostbyname(IP_ADDR);   /*域名也可以解析*/
		//server_addr.sin_addr = *((struct in_addr*)host->h_addr);
		rt_memset(&(server_addr.sin_zero),0,sizeof(server_addr.sin_zero));

		/*连接到服务器*/
		if(connect(sock,(struct sockaddr*)(&server_addr),sizeof(struct sockaddr))==-1)
		{
			LOG_E("server connect fail");
			closesocket(sock);
			rt_free(recv_data);
			rt_thread_mdelay(2000);
			continue;
		}
		else
		{
			LOG_I("server connect successful");
		}
		while (1)
		{		
			bytes_received=recv(sock,recv_data,TCPRV_BUFSZ-1,0);
			if(bytes_received<0)
			{
				closesocket(sock);
				LOG_E("received error,close the socket");
				break;
			}
			else if(bytes_received==0)
			{//目标地址已完成传输，并关闭连接
				LOG_W("received warning,recv function return 0");
				break;
			}
			
			/*有收到数据，把末尾清零*/
			recv_data[bytes_received]='\0';
			if(strncmp(recv_data,"q",1)==0||strncmp(recv_data,"Q",1)==0)
			{
				closesocket(sock);
				rt_free(recv_data);
				LOG_W("recv a 'q' or 'Q' ,client close the socket");
				break;
			}
			else
			{/*在终端显示收到的数据*/
				LOG_I("receive data = |%s|",recv_data);
			}

			int ret;
			ret=send(sock,send_data,strlen(send_data),0);
			if (ret<0)
			{
				closesocket(sock);
				rt_free(recv_data);
				LOG_E("send error,close the socket");
				break;
			}else if(ret==0)
			{
				LOG_W("send warning,send function return 0");
			}
			rt_thread_mdelay(50);
		}
	}
}
	
int tcp_client_thread_new(void)
{
	tcp_client_thread_ptr = rt_thread_create("tcpclient_th",tcp_client_thread,
							RT_NULL,1024,12,20);
	if(tcp_client_thread_ptr!=RT_NULL)
	{
		rt_thread_control(tcp_client_thread_ptr,RT_THREAD_CTRL_STARTUP,0);
	}
	return 0;
}
	


